package com.kbtd.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kbtd.constant.SystemConstants;
import com.kbtd.dto.Result;
import com.kbtd.entity.Shop;
import com.kbtd.mapper.ShopMapper;
import com.kbtd.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kbtd.utils.ILock;
import com.kbtd.utils.SimpleRedisLock;
import com.kbtd.utils.redis.RedisData;
import com.kbtd.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.kbtd.constant.RedisConstants.*;

/**
 *  商铺服务实现类
 *
 * @author wp
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;
    private static final Integer THREAD_POOL_SIZE = 10;
    private static final ExecutorService executor = Executors.
            newFixedThreadPool(THREAD_POOL_SIZE);

    @Autowired
    public ShopServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //热门商铺预热（热key预热）
    public Result setHotShop(Long[] ids) {
        List<Long> failIds = new ArrayList<>();
        for (Long id : ids) {
            String hotShopkey = RedisUtils.createKey(HOT_SHOP_KEY_PREFIX, id.toString());
            Shop shop = getById(id);
            if (shop == null) {
                failIds.add(id);
                continue;
            }
            String shopStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(hotShopkey, shopStr);
        }
        int fail = failIds.size();
        int success = ids.length - fail;
        String failIdsString = failIds.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        String res = String.format("总数据量%d条，成功%d条，失败%d条（%s）",
                ids.length, success, fail, failIdsString);
        return Result.ok(res);
    }

    //根据id查询商铺
    @Override
    public Result queryById(Long id) {
        Shop shop = getHotShopWithLogicExpire(id);
        if (shop == null) {
            //非热key情况
            shop = getShopWithBreakdown(id);
        }
        return Result.ok(shop);
    }

    //商铺更新
    //数据库缓存更新一致性问题：可选方案1先删缓存再更新数据库，方案2先更新数据库再更新缓存
    //为啥不使用更新缓存？
    // 1更新缓存业务更为复杂
    // 2访问频率不高的数据更新到缓存浪费内存
    // 3多次更新并发时可能存在不会使用中间更新数据，也就是说无效数据的更新
    //选择方案2？（共同弊端：前后操作之间访问数据存在脏读）
    //方案1：A线程删除缓存,B线程访问数据，缓存重建（脏数据）,A线程更新数据库，数据不一致
    //方案2：A线程更新数据库,B线程访问缓存旧值,A线程删除缓存，B线程将旧值插入缓存，数据不一致（概率低）
    //方案2可能问题：A线程更新数据库，删除缓存，B线程访问从库（旧值（主从同步未完成）），写入缓存旧值，数据不一致
    //延时双删：第一次删除是尽可能避免数据脏读（访问主库部分正常），第二次延时删除是为了保证主从同步完成，访问的数据均为最新数据
    //其他方案：订阅数据库变更日志，再操作缓存：使用canal订阅数据库binlog投递任务消息队列操作删除对应数据缓存（维护成本高）
    //最终强一致：需要加入锁机制，影响性能，与加缓存提升性能背驰（需跟据实际情况做取舍）
    //热点数据缓存更新：删除操作改为设置过期(延时双删)
    @Override
    public Result update(Shop shop) {
        //更新数据库
        updateById(shop);
        Thread delayedTask;
        Shop oldShop = getHotShopWithLogicExpire(shop.getId());
        if (oldShop == null) {
            //非热key情况
            //删除缓存
            String shopKey = RedisUtils.createKey(SHOP_KEY_PREFIX, shop.getId().toString());
            stringRedisTemplate.delete(shopKey);
            delayedTask = new Thread(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                stringRedisTemplate.delete(shopKey);
            });
        } else {
            //热key情况
            //设置过期
            String hotShopKey = RedisUtils.createKey(HOT_SHOP_KEY_PREFIX, shop.getId().toString());
            RedisData redisData = JSONUtil.toBean(hotShopKey, RedisData.class);
            redisData.setExpireTime(0L);
            String redisDataStr = JSONUtil.toJsonStr(redisData);
            stringRedisTemplate.opsForValue().set(hotShopKey, redisDataStr);
            delayedTask = new Thread(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                redisData.setExpireTime(0L);
                String newRedisDataStr = JSONUtil.toJsonStr(redisData);
                stringRedisTemplate.opsForValue().set(hotShopKey, newRedisDataStr);
            });
        }
        //延时删除任务
        executor.submit(delayedTask);
        return Result.ok();
    }

    //获取商铺（解决缓存穿透问题（存储NULL））
    //方案二采用分布式布隆过滤器（Redis实现）
    //布隆过滤器数据结构：二进制位数组 + 多组无偏hash（hash值分布均匀）函数
    //支持数据增加查询：设置或判断多组hash值对应位为1（存在误判（数据查询成功））
    public Shop getShopWithBreakdown(Long id) {
        String redisKey = RedisUtils.createKey(SHOP_KEY_PREFIX, id.toString());
        String shopStr = stringRedisTemplate.opsForValue().get(redisKey);
        Shop shop;
        if (shopStr == null) {
            //redis未查询到情况
            shop = getById(id);
            //添加缓存）
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(redisKey, NULL_VALUE, NULL_TTL, TimeUnit.SECONDS);
            } else {
                shopStr = JSONUtil.toJsonStr(shop);
                stringRedisTemplate.opsForValue().set(redisKey, shopStr, SHOP_TTL, TimeUnit.MINUTES);
            }
            return shop;
        } else if (NULL_VALUE.equals(shopStr)) {
            //redis查询存储为null情况
            return null;
        }
        //redis查询商铺存在
        shop = JSONUtil.toBean(shopStr, Shop.class);
        return shop;
    }

    //获取Hot商铺（热key解决缓存击穿问题（逻辑过期法））
    //判断缓存是否过期，是则新建线程进行缓存重建，返回过期数据，否则直接返回
    public Shop getHotShopWithLogicExpire(Long id) {
        String redisKey = RedisUtils.createKey(HOT_SHOP_KEY_PREFIX, id.toString());
        String redisDataStr = stringRedisTemplate.opsForValue().get(redisKey);
        if (redisDataStr == null) {
            //非热key情况
            return null;
        }
        RedisData redisData = JSONUtil.toBean(redisDataStr, RedisData.class);

        String lockKey = RedisUtils.createKey(LOCK_SHOP_KEY_PREFIX, id.toString());
        ILock shopLock = new SimpleRedisLock(lockKey, stringRedisTemplate);
        if (redisData.isExpire() && shopLock.tryLock(LOCK_SHOP_TTL)) {
            //过期
            Thread thread = new Thread(() -> {
                Shop shop = getById(id);
                //更新过期缓存数据，刷新过期时间
                RedisData newRedisData = new RedisData();
                newRedisData.setData(shop);
                newRedisData.setExpireTime(SHOP_TTL);
                String newRedisDataStr = JSONUtil.toJsonStr(redisData);
                stringRedisTemplate.opsForValue().set(redisKey, newRedisDataStr);
                //释放锁
                shopLock.unlock();
            });
            executor.submit(thread);
        }
        return redisData.getData(Shop.class);
    }

    //商铺位置数据预热
    @Override
    public void preheatShopPosition() {

        List<Shop> shops = query().list();
        Map<Long, List<Shop>> shopMap = shops.stream().collect(Collectors.groupingBy(Shop::getTypeId));
        for (Long typeId : shopMap.keySet()) {
            String geoKey = RedisUtils.createKey(SHOP_GEO_KEY_PREFIX, typeId.toString());
            for (Shop shop : shopMap.get(typeId)) {
                stringRedisTemplate.opsForGeo().add(geoKey,
                        new Point(shop.getX(), shop.getY()),
                        shop.getId().toString());
            }
        }
    }

    //根据类型查询附近商铺
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double longitude, Double latitude) {
        //判断是否需要根据距离查询
        if (longitude == null || latitude == null) {
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        //附近查询
        //分页参数
        int start = PageUtil.getStart(current, SystemConstants.DEFAULT_PAGE_SIZE);
        int end = PageUtil.getEnd(current, SystemConstants.DEFAULT_PAGE_SIZE);
        String key = RedisUtils.createKey(SHOP_GEO_KEY_PREFIX, typeId.toString());
        //半径
        double radius = 5000;
        Circle circle = new Circle(longitude, latitude, radius);
        GeoResults<RedisGeoCommands.GeoLocation<String>> shopPoints =
                stringRedisTemplate.opsForGeo().radius(key, circle);

        if (ObjectUtils.isEmpty(shopPoints) || shopPoints.getContent().isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        //确保不超出范围
        int size = shopPoints.getContent().size();
        if (start >= size) {
            return Result.ok(Collections.emptyList());
        }
        end = Math.min(end, size); // 确保end不超过ids的大小

        List<Long> ids = shopPoints.getContent().stream()
                .map(point -> point.getContent().getName())
                .map(Long::valueOf)
                .collect(Collectors.toList()).subList(start, end);

        List<Double> distance = shopPoints.getContent().stream()
                .map(point -> point.getDistance().getValue())
                .collect(Collectors.toList());

        String idsStr = StrUtil.join(",", ids);

        List<Shop> shops = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idsStr + ")")
                .list();

        for (int i = 0; i < shops.size(); i++) {
            // 设置shop的距离属性
            shops.get(i).setDistance(distance.get(start + i));
        }

        return Result.ok(shops);
    }

}
